#!/usr/bin/env ruby

class Box

  BOX_API_KEY = "YOUR_API_KEY"
  BOX_LOGIN_EMAIL = "YOUR LOGIN EMAIL" # use '%40' instead of '@'
  BOX_PASSWORD = "YOUR PASSWORD"
  BOX_FOLDER_ID = 0 # upload to the root folder, 0 is root folder id
  BOX_GET_TICKET_URL = "http://www.box.net/api/1.0/rest?action=get_ticket&api_key=#{BOX_API_KEY}"
  BOX_AUTH_URL = "http://www.box.net/api/1.0/auth/"
  BOX_GET_AUTH_TOKEN_URL = "http://www.box.net/api/1.0/rest?action=get_auth_token&api_key=#{BOX_API_KEY}&ticket="
  BOX_TREE_URL = "http://www.box.net/api/1.0/rest?action=get_account_tree&api_key=#{BOX_API_KEY}&params%5B%5D=nozip&auth_token="
  BOX_UPLOAD_URL = "http://upload.box.net/api/1.0/upload/%s/#{BOX_FOLDER_ID}"
  BOX_PUBLIC_SHARE_URL = "http://www.box.net/api/1.0/rest?action=public_share&api_key=#{BOX_API_KEY}&auth_token="
  BOX_SHARE_URL = "http://www.box.net/shared/"

  def ticket
    puts "authenticating ..."
    @ticket_xml = `curl -s '#{BOX_GET_TICKET_URL}'`
    @ticket_xml =~ /<ticket>([a-z0-9]+)<\/ticket>/
    @ticket = $1
    login_page = `curl -s '#{BOX_AUTH_URL}'`
    login_page =~ /<input type="hidden" style="display: none;" name="request_token" value="([a-z0-9]+)"\/>/i
    request_token = $1
    param = "login=#{BOX_LOGIN_EMAIL}&password=#{BOX_PASSWORD}&dologin=1&__login=1&request_token=#$1"
    `curl -s -d '#{param}' '#{BOX_AUTH_URL}#@ticket'`
  end

  def auth_token
    @auth_token_xml = `curl -s '#{BOX_GET_AUTH_TOKEN_URL}#{@ticket}'`
    @auth_token_xml =~ /<auth_token>([a-z0-9]+)<\/auth_token>/
    @auth_token = $1
  end

  def folders(folder_id)
    url = "#{BOX_TREE_URL}#{@auth_token}&folder_id=#{folder_id}"
    `curl -s '#{url}'`
  end

  def upload(filepath)
    puts "uploading #{filepath} ... "
    url = BOX_UPLOAD_URL % @auth_token
    @upload_xml = `curl -s -F 'new_file1=@#{filepath}' '#{url}'`
    @upload_xml =~ / id="(\d+)" /
    @upload = $1
  end

  def public(id=nil,type="file")
    puts "processing ..."
    id ||= @upload
    url = "#{BOX_PUBLIC_SHARE_URL}#{@auth_token}&target=#{type}&target_id=#{id}&password=&message=&emails%5B%5D="
    @public_xml = `curl -s '#{url}'`
    @public_xml =~ /<public_name>([a-z0-9]+)<\/public_name>/
    @public = $1
    "#{BOX_SHARE_URL}#@public"
  end

end

# capture screen
tmpfile = "#{`mktemp -u`.strip}.png"
`scrot -s #{tmpfile}`
targetfile="#{`zenity --file-selection --save --confirm-overwrite 2> /dev/null`.strip}.png"
`mv #{tmpfile} #{targetfile}`

# upload it to box.net
box = Box.new
box.ticket
box.auth_token
box.upload(targetfile)
`firefox '#{box.public}'`
